package com.example.foodwebbackend.controller;

import com.example.foodwebbackend.dto.ApiResponse;
import com.example.foodwebbackend.dto.LoginRequest;
import com.example.foodwebbackend.dto.RegisterRequest;
import com.example.foodwebbackend.entity.Admin;
import com.example.foodwebbackend.entity.Merchant;
import com.example.foodwebbackend.entity.User;
import com.example.foodwebbackend.service.AdminService;
import com.example.foodwebbackend.service.MerchantService;
import com.example.foodwebbackend.service.UserService;
import com.example.foodwebbackend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 统一注册接口
     */
    @PostMapping("/register")
    public ApiResponse<?> register(@RequestBody RegisterRequest request) {
        try {
            if (request.getUsername() == null || request.getPassword() == null || request.getUserType() == null) {
                return ApiResponse.error("请填写完整信息");
            }

            Map<String, Object> result = new HashMap<>();
            String token;

            switch (request.getUserType()) {
                case "user":
                    User user = userService.register(request.getUsername(), request.getPassword());
                    token = jwtUtil.generateToken(user.getUsername(), "user", user.getUserId());
                    result.put("token", token);
                    result.put("user", user);
                    result.put("userType", "user");
                    break;

                case "merchant":
                    if (request.getMerchantName() == null || request.getMerchantAddress() == null || 
                        request.getContactPhone() == null) {
                        return ApiResponse.error("商家注册信息不完整");
                    }
                    
                    if (request.getContactPhone().length() > 20) {
                        return ApiResponse.error("联系电话不能超过20个字符");
                    }
                    
                    Merchant merchant = merchantService.register(
                        request.getUsername(), 
                        request.getPassword(),
                        request.getMerchantName(),
                        request.getMerchantAddress(),
                        request.getContactPhone(),
                        request.getBusinessHours(),
                        request.getMerchantDescription()
                    );
                    
                    token = jwtUtil.generateToken(merchant.getUsername(), "merchant", merchant.getMerchantId());
                    result.put("token", token);
                    result.put("merchant", merchant);
                    result.put("userType", "merchant");
                    result.put("message", "商家注册成功，请等待审核");
                    break;

                default:
                    return ApiResponse.error("不支持的用户类型");
            }

            return ApiResponse.success("注册成功", result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 统一登录接口
     */
    @PostMapping("/login")
    public ApiResponse<?> login(@RequestBody LoginRequest request) {
        try {
            if (request.getUsername() == null || request.getPassword() == null || request.getUserType() == null) {
                return ApiResponse.error("请填写完整登录信息");
            }

            Map<String, Object> result = new HashMap<>();
            String token;

            switch (request.getUserType()) {
                case "user":
                    User user = userService.login(request.getUsername(), request.getPassword());
                    token = jwtUtil.generateToken(user.getUsername(), "user", user.getUserId());
                    result.put("token", token);
                    result.put("user", user);
                    result.put("userType", "user");
                    break;

                case "merchant":
                    Merchant merchant = merchantService.login(request.getUsername(), request.getPassword());
                    token = jwtUtil.generateToken(merchant.getUsername(), "merchant", merchant.getMerchantId());
                    result.put("token", token);
                    result.put("merchant", merchant);
                    result.put("userType", "merchant");
                    break;

                case "admin":
                    Admin admin = adminService.login(request.getUsername(), request.getPassword());
                    token = jwtUtil.generateToken(admin.getAdminUsername(), "admin", admin.getAdminId());
                    result.put("token", token);
                    result.put("admin", admin);
                    result.put("userType", "admin");
                    break;

                default:
                    return ApiResponse.error("不支持的用户类型");
            }

            return ApiResponse.success("登录成功", result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    public ApiResponse<?> checkUsername(@RequestParam String username, @RequestParam String userType) {
        boolean exists = false;
        
        switch (userType) {
            case "user":
                exists = userService.existsByUsername(username);
                break;
            case "merchant":
                exists = merchantService.existsByUsername(username);
                break;
            case "admin":
                exists = adminService.existsByUsername(username);
                break;
        }
        
        return ApiResponse.success(exists);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ApiResponse<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        try {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            String username = jwtUtil.getUsernameFromToken(token);
            String userType = jwtUtil.getUserTypeFromToken(token);
            
            Map<String, Object> result = new HashMap<>();
            
            switch (userType) {
                case "user":
                    User user = userService.findByUsername(username);
                    if (user == null) {
                        return ApiResponse.unauthorized("用户不存在");
                    }
                    result.put("user", user);
                    result.put("userType", "user");
                    break;
                    
                case "merchant":
                    Merchant merchant = merchantService.findByUsername(username);
                    if (merchant == null) {
                        return ApiResponse.unauthorized("商家不存在");
                    }
                    result.put("merchant", merchant);
                    result.put("userType", "merchant");
                    break;
                    
                case "admin":
                    Admin admin = adminService.findByUsername(username);
                    if (admin == null) {
                        return ApiResponse.unauthorized("管理员不存在");
                    }
                    result.put("admin", admin);
                    result.put("userType", "admin");
                    break;
                    
                default:
                    return ApiResponse.unauthorized("无效的用户类型");
            }
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.unauthorized("无效的token");
        }
    }


} 